#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);

  QSettings appSettings(QDir::currentPath() + "/settings.ini",QSettings::IniFormat,0);

  networkConnectAttemptCount = 0;

  //Load settings from the settings.ini file
  loadSettings(appSettings);

  //this->setWindowFlags(Qt::MSWindowsFixedSizeDialogHint); //Set window to fixed size
  //this->setWindowFlags(Qt::CustomizeWindowHint); //Set window with no title bar
  //this->setWindowFlags(Qt::FramelessWindowHint); //Set a frameless window
  networkClient = new NetworkClient();
  amplifierData = new AmplifierData();

  networkClient->configureNetwork(jsonSettings);

  connect(networkClient,SIGNAL(dataReady(QByteArray)), this, SLOT(networkDataReady(QByteArray)));
  connect(networkClient, SIGNAL(socketError(int,QString)), this, SLOT(networkError(int,QString)));
}

MainWindow::~MainWindow() {
  delete ui;
}

void MainWindow::loadSettings(QSettings &settings) {
  //With all the settings we try to load we first check that
  //each key does exist. If not then we write the default value
  //of it to the settings file to make sure we add keys to an old
  //settings file

  // ==== Network Settings START ====
  settings.beginGroup("Network");

  if (settings.contains("ServerIP") == 0) {
    settings.setValue("ServerIP",DEFAULT_NETWORK_SERVER_IP);
  }
  jsonSettings["NetworkServerIP"] = settings.value("ServerIP").toString();

  if (settings.contains("ServerPort") == 0) {
    settings.setValue("ServerPort",DEFAULT_NETWORK_SERVER_PORT);
  }
  jsonSettings["NetworkServerPort"] = settings.value("ServerPort").toInt();

  if (settings.contains("ConnectAttempts") == 0) {
    settings.setValue("ConnectAttempts",DEFAULT_NETWORK_CONNECT_ATTEMPTS);
  }
  jsonSettings["NetworkConnectAttempts"] = settings.value("ConnectAttempts").toInt();

  if (settings.contains("ConnectTimeout") == 0) {
    settings.setValue("ConnectTimeout",DEFAULT_NETWORK_CONNECT_TIMEOUT);
  }
  jsonSettings["NetworkConnectTimeout"] = settings.value("ConnectTimeout").toInt();

  settings.endGroup();
  // ==== Network Settings END ====

  // ==== PowerMeter Settings START ====
  settings.beginGroup("PowerMeter");

  if (settings.contains("PowerMeterBufferListSize") == 0) {
    settings.setValue("PowerMeterBufferListSize",DEFAULT_POWERMETER_BUFFER_LIST_SIZE);
  }
  jsonSettings["PowerMeterBufferListSize"] = settings.value("PowerMeterBufferListSize").toInt();

  settings.endGroup();
  // ==== PowerMeter Settings END ====
}

void MainWindow::on_pushButtonConnect_clicked() {
  networkClient->connectToHost();
}

void MainWindow::on_pushButtonDisconnect_clicked() {
  networkClient->disconnectFromHost();
}

void MainWindow::networkDataReady(QByteArray data) {
  QJsonDocument jsonDocument;
  QJsonObject jsonObj;

  jsonDocument = QJsonDocument(QJsonDocument::fromBinaryData(data));
  jsonObj = jsonDocument.object();

  switch(jsonObj["NetworkDataType"].toInt()) {
    case NETWORK_DATA_TYPE_POWERMETER:
      amplifierData->setPowerMeterParameters(jsonDocument);
      updateGUI(GUI_UPDATE_POWERMETER);
      break;
    default:
      break;
  }
}

void MainWindow::updateGUI(quint8 type) {
  if ((type == GUI_UPDATE_ALL) || (type == GUI_UPDATE_POWERMETER)) {
    ui->progressBarFWDPower->setValue(amplifierData->getPowerMeterFWDPower());
    ui->progressBarREFPower->setValue(amplifierData->getPowerMeterREFPower());

    listPowerMeterFWDPower.append(amplifierData->getPowerMeterFWDPower());
    listPowerMeterREFPower.append(amplifierData->getPowerMeterREFPower());

    //Keep the size of the power meter buffer at a max size so we can find the
    //Maximum value and display that as text
    if (listPowerMeterFWDPower.count() > jsonSettings["PowerMeterBufferListSize"].toDouble()) {
      listPowerMeterFWDPower.removeFirst();
      listPowerMeterREFPower.removeFirst();
    }

    quint16 max_size=0;
    quint8 max_size_pos=0;

    for (quint8 i=0;i<listPowerMeterFWDPower.count();i++) {
      if (listPowerMeterFWDPower.at(i) > max_size) {
        max_size = listPowerMeterFWDPower.at(i);
        max_size_pos = i;
      }
    }

    ui->labelFWDPowerValue->setText(QString::number(listPowerMeterFWDPower.at(max_size_pos))+"W");
    ui->labelREFPowerValue->setText(QString::number(listPowerMeterREFPower.at(max_size_pos))+"W");
  }
}

void MainWindow::networkError(const int &errorCode, const QString &errorString) {
  qDebug() << "Network: ERROR >> " << errorString;
}
